using System;
using System.Collections.Generic;
using System.Configuration;
using System.Text;
using Spring.Context.Support;
using Xtee.Core.Adapter.Service.Config;
using Xtee.Core.Utils;


namespace Xtee.Core.Spring.Adapter.Config
{
    public class XteeServiceTypeValidator : ConfigurationValidatorBase
    {

        public override void Validate(object value)
        {
            if(value.ToString()==string.Empty) return;
            if (ContextRegistry.GetContext().ContainsObject(value.ToString()))
            {
                object service = ContextRegistry.GetContext().GetObject(value.ToString());
                if (service.GetType().GetInterface("IXteeServiceHandler`2") == null)
                {
                    throw new ConfigurationErrorsException("Service (" + Type.GetType((string)value).FullName + ") must implement  Xtee.Adapter.IXteeServiceHandler ");
                }

                else
                    return;

            }
 
        }

        public override bool CanValidate(Type type)
        {
            return type.Name == "String";
        }
    }

    public sealed class XteeOperationConfigElement : AbstractXteeOperationConfigElement, IXteeOperationInfo
    {
 
        public static XteeOperationConfigElement Parse(string operationqualifiedname)
        {
            AssertUtils.IsServiceCodeValid(operationqualifiedname);
            string[] vals = operationqualifiedname.Split(new char[] { '.' });
            XteeOperationConfigElement info = new XteeOperationConfigElement();
            info.Name = vals[1];
            info.Version = vals[2];
            info.Producer = vals[0];
            return info;
        }


        public XteeOperationConfigElement()
        {

        }

        public XteeOperationConfigElement(string name):base(name)
        { 
        }
        public XteeOperationConfigElement(string producer, string name, string version):base(producer,name,version)
        {
            
        }

         
        /// <summary>
        /// Service which handles   operation requested
        /// </summary>
        [ConfigurationProperty("value-ref", IsRequired = true)]
        [ConfigurationValidator(typeof(XteeServiceTypeValidator))]
        public string Service
        {
            get
            {

                return (string)this["value-ref"];

            }

            set
            {
                this["value-ref"] = value;
            }

        }
       

    }
}